package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.sun.org.apache.bcel.internal.generic.I2D;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    //建立线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {

        //Shop shop = queryWithLogicalTime(id);
        //使用自定义泛型方法代替以上调用方式
        Shop shop = cacheClient.getPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, 30L, TimeUnit.MINUTES);

        if(shop == null){
            return Result.fail("商户不存在");
        }
        return Result.ok(shop);

    }
    public void saveShop2Redis(Long id, Long expireSeconds){
        Shop shop = getById(id);
        RedisData redisData = new RedisData();

        //构建新的数据类型，传入逻辑过期时间
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id , JSONUtil.toJsonStr(redisData));
    }

    //解决缓存击穿: 逻辑过期方案
    private Shop queryWithLogicalTime(Long id){

        //1 从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //2 判断是否存在
        if(StrUtil.isBlank(shopJson)){
            //2.1 不存在, 返回null
            return null;
        }

        //2.2 存在，判断缓存逻辑时间是否过期
        //shopJson反序列化为Shop对象
        RedisData data = JSONUtil.toBean(shopJson, RedisData.class);
        LocalDateTime expireTime = data.getExpireTime();

        JSONObject json = (JSONObject) data.getData();
        Shop shop = JSONUtil.toBean(json, Shop.class);

        if(expireTime.isAfter(LocalDateTime.now())){
            //2.2.1 未过期，直接返回店铺信息
            return shop;
        }

        //2.2.2 过期，重建缓存信息
        //3 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);

        if(isLock){
            //开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //模拟延迟
                    Thread.sleep(200);
                    //重建缓存
                    saveShop2Redis(id, 20L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });

        }
        return shop;
    }

    //解决缓存击穿: 互斥锁方案
    private Shop queryWithMutex(Long id){
        //1 从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //2 判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
            //2.1 存在, 且不为空串
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            //return Result.ok(shop);
            return shop;
        }

        //2.1.1 不为null, 但为空字符串，防止缓存击穿
        if("".equals(shopJson)){
            //return Result.fail("商户不存在");
            return null;
        }

        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            //获取互斥锁
            boolean isLock = tryLock(lockKey);
            //判断是否获取到锁
            if(!isLock){
                //否，休眠，并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //是，查询数据库

            //2.2 不存在，根据id查数据库
            shop = getById(id);
            //模拟缓存重建延迟
            Thread.sleep(200);

            if(shop==null){
                //3 数据库不存在，在redis存储空值，防止缓存穿透
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                //return Result.fail("商户不存在");
                return null;
            }

            //4 数据库存在
            //4.1 数据同步缓存到redis
            //缓存有效期
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id , JSONUtil.toJsonStr(shop), 30L, TimeUnit.MINUTES);


        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {

            //释放锁
            unlock(lockKey);
        }

        //4.2 数据库返回数据给前端
        //return Result.ok(shop);
        return shop;
    }


    //解决缓存穿透的方案
    private Shop queryWithPassThrough(Long id){
        //1 从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //2 判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
            //2.1 存在, 且不为空串
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            //return Result.ok(shop);
            return shop;
        }

        //2.1.1 不为null, 但为空字符串，防止缓存击穿
        if("".equals(shopJson)){
            //return Result.fail("商户不存在");
            return null;
        }

        //是，查询数据库

        //2.2 不存在，根据id查数据库
        Shop shop = getById(id);

        if(shop==null){
            //3 数据库不存在，在redis存储空值，防止缓存穿透
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //return Result.fail("商户不存在");
            return null;
        }

        //4 数据库存在
        //4.1 数据同步缓存到redis
        //缓存有效期
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id , JSONUtil.toJsonStr(shop), 30L, TimeUnit.MINUTES);


        //4.2 数据库返回数据给前端
        //return Result.ok(shop);
        return shop;
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private boolean unlock(String key){
        Boolean ifDelete = stringRedisTemplate.delete(key);
        return BooleanUtil.isTrue(ifDelete);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        //1 更新数据库
        updateById(shop);

        //2 删除redis缓存
        Long id = shop.getId();
        if(id == null){
            Result.fail("店铺ID为空");
        }
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id );

        //3 返回结果
        return Result.ok();

    }
}
